package com.jjty.dataGenerator.jshjy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jjty.dataGenerator.jserji.entity.ApiResponse;
import com.jjty.dataGenerator.jshjy.entity.JsAttendanceData;
import com.jjty.dataGenerator.jshjy.mapper.JsAttendanceDataMapper;
import com.jjty.dataGenerator.jshjy.utils.PushHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class AttendancePushService {

    @Autowired
    private JsAttendanceDataMapper attendanceDataMapper;
    @Autowired
    private PushHttpClient pushHttpClient;
    @Value("${jsedu.channel}")
    private String channel;

    /**
     * 批量推送考勤数据（按未推送状态筛选）
     * @param limit 批量推送数量
     * @return 推送结果统计
     */
    public String pushBatchAttendance(int limit) {
        QueryWrapper<JsAttendanceData> query = new QueryWrapper<>();
        query.eq("push_status", 0)
             .last("LIMIT " + limit);
        List<JsAttendanceData> dataList = attendanceDataMapper.selectList(query);
        
        if (dataList.isEmpty()) {
            return "无待推送的考勤数据";
        }

        int successCount = 0;
        int totalCount = dataList.size();
        
        for (JsAttendanceData data : dataList) {
            // 转换为接口请求体（匹配文档中考勤数据字段）
            JsAttendanceData request = new JsAttendanceData();
            request.setChannel(channel);
            request.setImeiNo(data.getImeiNo());
            request.setRecordTime(data.getRecordTime());
            request.setType(data.getType()); // 1：进校、2：离校等（字符串类型）
            request.setState(data.getState()); // 1：正常、2：迟到等（字符串类型）

            ApiResponse response = pushHttpClient.push(
                "/openapi/stu-card/sync/attendance", 
                request
            );

            data.setPushTime(LocalDateTime.now());
            if (response.getCode() == 0) {
                data.setPushStatus(1);
                data.setPushMsg("批量推送成功");
                successCount++;
            } else {
                data.setPushStatus(2);
                data.setPushMsg("失败原因：" + response.getMsg());
            }
            attendanceDataMapper.updateById(data);
        }

        return String.format("考勤数据批量推送完成，总条数：%d，成功：%d，失败：%d",
            totalCount, successCount, totalCount - successCount);
    }
}